package com.metaverse.backend.security;

import com.metaverse.backend.domain.User;
import com.metaverse.backend.enums.UserStatus;
import com.metaverse.backend.repo.UserRepo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@AllArgsConstructor
@Slf4j
@Service("jwtUserDetailsService")
public class JwtUserDetailsService implements UserDetailsService {
    private UserRepo userRepo;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepo.findByUsername(username);

        if (user == null) {
            log.error("尝试登录的用户不存在：" + username);
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        }

        if(user.getStatus() != UserStatus.NORMAL){
            log.error("尝试登录的用户状态不正确：" + username + "," + user.getStatus());
            throw new IllegalStateException("用户状态不正确["+user.getStatus().getDescription()+"]");
        }

        return JwtUserFactory.create(user);

    }


}
